<template>
  <div class="maincontent">
    <HeaderSelector></HeaderSelector>

    <!--这里用了elementUI的样式-->
    <div class="mblog">

      <el-row>
        <el-col :span="16">
          <h2> {{ blog.title }}</h2>
        </el-col>
        <el-col :span="8" class="bauthor">
          <!--          <el-avatar :src="blog.avatar"-->
          <!--                     size="medium">-->
          <!--          </el-avatar>-->
          <div>
            <i class="el-icon-user-solid"></i> {{ blog.author }}
          </div>
        </el-col>
      </el-row>
      <!--编辑按钮-->
      <!--    只有当前用户能看到   v-if   -->
      <!--      <el-link icon="el-icon-edit" v-if="ownBlog">-->
      <!--        &lt;!&ndash;同理传参&ndash;&gt;-->
      <!--        <router-link :to="{name: 'BlogEdit', params: {blogId: blog.id}}">-->
      <!--          编辑-->
      <!--        </router-link>-->
      <el-button v-if="ownBlog" @click="edit(blog.id)" icon="el-icon-edit" type="primary"></el-button>
      <!--      </el-link>-->
      <el-button v-if="ownBlog" @click="del(blog.id)" icon="el-icon-delete" type="danger"></el-button>


      <!--      &nbsp;-->
      <!--分割线-->
      <el-button class="like" v-if="!isLike" type="success" icon="el-icon-arrow-up" circle @click="like"
                 title="给我点赞"></el-button>
      <el-button class="like" v-if="isLike" type="success" icon="el-icon-caret-top" circle @click="dislike"
                 title="取消点赞"></el-button>
      <el-button type="warning" v-if="!isCollected" icon="el-icon-star-off" circle @click="collect"
                 title="收藏文章"></el-button>
      <el-button type="warning" v-if="isCollected" icon="el-icon-star-on" circle @click="disCollect"
                 title="取消收藏"></el-button>
      <el-upload v-if="ownBlog"
                 class="upload-demo"
                 :before-upload="BeforeUploadVideo"
                 :http-request="UploadVideo"
                 action="">
        <el-button type="text">上传视频</el-button>
      </el-upload>

      <el-divider v-if="hasVideo"></el-divider>

      <!--视频组件-->
      <video-player v-if="hasVideo" class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true"
                    :options="playerOptions"></video-player>

      <el-divider></el-divider>
      <!--文章内容  html格式-->
      <!--class="markdown-body"  使用了样式
        需要import 'github-markdown-css'
      -->
      <!--      <div class="markdown-body" v-html="blog.content"></div>-->
      <mavon-editor
          :value="blog.content"
          defaultOpen="preview"
          :boxShadow="false"
          style="z-index:1;"
          :editable="false"
          :subfield="false"
          :toolbarsFlag="false"
      >
      </mavon-editor>
    </div>

    <!--评论-->
    <div class="mComment">

      <el-popover
          placement="right"
          width="400"
          trigger="click">

        <el-form :model="pform" :rules="rules" ref="pform" label-width="70px" class="demo-ruleForm">
          <el-form-item label="留言" prop="content">
            <el-input placeholder="请讲" v-model="pform.content" type="textarea" :rows="3"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitPform('pform')">确定</el-button>
          </el-form-item>
        </el-form>


        <el-button slot="reference">留言</el-button>
      </el-popover>

      <br><br>
      <el-card shadow="hover" v-for="pcomment in pcomments">

        <el-row>
          <el-col :span="12">

          </el-col>
          <el-col :span="12">
            <div class="commentTime">
              {{ pcomment.created }}
            </div>
          </el-col>
          <el-col :span="12" class="pcommentavatar">
            <i class="el-icon-user"></i>
            {{ pcomment.author }}
          </el-col>
        </el-row>

        <br>
        <el-row>
          <el-col :span="18">
            {{ pcomment.content }}
          </el-col>
          <el-col :span="6" class="huifu">
            <el-button type="text" @click="transportId(pcomment.cid)">回复</el-button>
          </el-col>
        </el-row>
      </el-card>

      <el-dialog
          title="回复"
          :visible.sync="dialogVisible"
          width="30%">

        {{ parentContent }}
        <br>
        <br>

        <el-input
            :rows="2"
            placeholder="请说"
            v-model="ccommentContent"
            @keyup.enter.native="sendCcomment"
        >
        </el-input>
        <!--子评论-->
        <br>
        <br>
        <el-card shadow="hover" v-for="ccomment in ccomments">

          <el-row>
            <el-col :span="12">

            </el-col>
            <el-col :span="12">
              <div class="commentTime">
                {{ ccomment.created }}
              </div>
            </el-col>
            <el-col :span="12" class="pcommentavatar">
              <i class="el-icon-user"></i>
              {{ ccomment.author }}
            </el-col>
          </el-row>
          {{ ccomment.content }}


          <!--          <div class="commentLast">-->

          <el-popover
              class="commentLast"
              placement="bottom"
              title="友善评论"
              width="200"
              trigger="click">
            <el-input v-model="commentLasContetn"></el-input>
            <el-button @click="commentLast(ccomment.uid)">确定</el-button>
            <el-button type="text" slot="reference">回复</el-button>

          </el-popover>
          <!--          </div>-->

        </el-card>


        <!--子评论分页-->
        <el-pagination class="mpage"
                       background
                       layout="prev, pager, next"
                       :current-page="ccurrentPage"
                       :page-size="cpageSize"
                       :total="ctotal"
                       @current-change=page>
        </el-pagination>

        <!--        <span slot="footer" class="dialog-footer">-->
        <!--    <el-button @click="dialogVisible = false">取 消</el-button>-->
        <!--    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>-->
        <!--    </span>-->
      </el-dialog>


      <!--分页组件-->
      <!--关键属性：
        current-page
        page-size
        total
        点击分页的事件：@current-change
        -->
      <el-pagination class="mpage"
                     background
                     layout="prev, pager, next"
                     :current-page="currentPage"
                     :page-size="pageSize"
                     :total="total"
                     @current-change=page>
      </el-pagination>


      <br>
      <br>
      <h3>推荐</h3>

      <el-card v-for="recommend in recommends" class="recommend" @click.native="toDetail(recommend.id)">
        <h4>{{ recommend.title }}</h4>
        {{ recommend.description }}
        <br>
      </el-card>

    </div>
  </div>
</template>

<script>
import 'github-markdown-css'
import HeaderSelector from "../components/HeaderSelector";

import "video.js/dist/video-js.css";
import {videoPlayer} from "vue-video-player";
import Router from "vue-router";
import Login from "./Login";

export default {
  inject: ["reload"],
  name: "BlogDetail.vue",
  components: {HeaderSelector, videoPlayer},

  data() {
    return {

      dialogVisible2: false,

      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4",
            src: '', //视频url地址
          },
        ],
        // poster: require("../assets/Index/video01.png"), //你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true, //全屏按钮
        },
      },

      hasVideo: false,

      blog: {
        id: "",
        title: "",
        content: "",
        avatar: "",
        author: '',
      },
      ownBlog: false,   //用于是否显示编辑按钮

      isLike: true,  //是否点过赞
      isCollected: true, //是否收藏过

      pcomments: {}, //父评论
      ccomments: {},  //子评论

      //准备发送的父评论
      pform: {
        bid: '',
        content: '',
      },
      //准备发送的子评论
      cform: {
        parentCid: '',
        content: '',
      },

      clastform: {
        parentCid: '',
        content: '',
        touser: '',
      },

      commentLasContetn: "",

      rules: {
        content: [
          {required: true, message: '你还没有填写内容哦', trigger: 'blur'},
        ]
      },


      dialogVisible: false, //分类
      // metasFromFront: [],  //前台选中发送给后端的
      radio: '',   //还是改成单选

      metasFromBack: [],//从后台来的metas

      //父评论分页
      currentPage: 1,
      currentPage_s: 1,
      total: 0,
      pageSize: 5,

      //子评论用
      commentId: '',  //父评论id
      //子评论分页
      ccurrentPage: 1,
      ccurrentPage_s: 1,
      ctotal: 0,
      cpageSize: 5,
      ccommentContent: '',

      recommends: [],

      parentContent: '',


      //用于视频上传
      videoFile: new FormData(),

    }
  },
  methods: {
    //父评论分页
    page(currentPage) {
      this.$axios.get('/findParentComment/' + this.blog.id + "?currentPage=" + currentPage).then(res => {
        this.pcomments = res.data.data.records
        this.currentPage = res.data.data.current
        this.total = res.data.data.total
        this.pageSize = res.data.data.size
      })
    },

    //子评论分页
    cpage(currentPage) {
      this.$axios.get('/findChildComment/' + this.commentId + "?currentPage=" + currentPage).then(res => {
        this.ccomments = res.data.data.records
        this.ccurrentPage = res.data.data.current
        this.ctotal = res.data.data.total
        this.cpageSize = res.data.data.size
      })
    },

    edit(blogId) {   //push传参
      this.$router.push({
        name: 'BlogEdit',
        params: blogId
      })
    }
    ,
    del(blogId) {   //push传参
      this.$axios.delete('/delBlogById/' + blogId, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        console.log('删除成功')
        //删除成功
        this.$message({type: "success", message: "删除成功"})
        //跳转到
        this.$router.go(-1);
      })
    }
    ,
    like() {
      this.$axios.get('/likeBlog/' + this.blog.id, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {

        this.$message({type: "success", message: "点赞成功"})

        this.isLike = true

      })
    }
    ,
    dislike() {
      this.$axios.get('/dislikeBlog/' + this.blog.id, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        this.$message({type: "success", message: "已取消点赞"})

        this.isLike = false
      })
    },

    collect() {
      this.$axios.post('/addBlogCollection?bid=' + this.blog.id, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        this.$message({type: "success", message: "收藏成功"})

        this.isCollected = true
      })
    },

    disCollect() {
      this.$axios.delete('/delCollection?bid=' + this.blog.id, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        this.$message({type: "success", message: "已取消收藏"})

        this.isCollected = false
      })
    },

    submitPform(pform) {
      this.$refs[pform].validate((valid) => {
            if (valid) {
              //登录前台检测
              if (localStorage.getItem("token") == null || localStorage.getItem("token") == '') {
                //没登陆
                this.$message({
                  message: '请先登录',
                  type: 'warning'
                })
              } else {
                this.$axios.post('/commentParent', this.pform, {
                  headers: {
                    "Authorization": localStorage.getItem("token")
                  }
                }).then(res => {
                  this.$message({message: "评论成功", type: 'success'})
                  this.reload();
                })
              }
            } else {
              this.$message("填写有误")
            }
          }
      )
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
    }
    ,


    //子评论  传输id
    transportId(id) {
      this.dialogVisible = true
      this.commentId = id
      //展示父评论
      this.$axios.get("/findParentCommentById/" + id).then(res => {

        this.parentContent = res.data.data.content
      })

      //然后要回显所有的子评论
      this.cpage(1)
    },

    //子评论发送
    sendCcomment() {
      //组成表单
      this.cform.parentCid = this.commentId
      this.cform.content = this.ccommentContent
      console.log("parentCid = " + this.cform.parentCid)
      console.log("content = " + this.cform.content)
      //登录前台检测
      if (localStorage.getItem("token") == null || localStorage.getItem("token") == '') {
        //没登陆
        this.$message({
          message: '请先登录',
          type: 'warning'
        })
      } else {
        this.$axios.post('/commentChild', this.cform, {
          headers: {
            "Authorization": localStorage.getItem("token")
          }
        }).then(res => {
          this.$message({message: "回复成功", type: 'success'})
          this.reload();
          //发送完清空一下content
          this.cform.parentCid = ''
          this.commentId = ''
          this.cform.content = ''
          this.ccommentContent = ''
        })
      }
    },

    //给子评论评论  21/10/13
    commentLast(uid) {
      //组成表单
      // this.clastform.parentCid = this.commentId
      // this.clastform.content = this.ccommentContent
      // this.clastform.touser = author
      console.log(uid)


      //登录前台检测
      /*if (localStorage.getItem("token") == null || localStorage.getItem("token") == '') {
        //没登陆
        this.$message({
          message: '请先登录',
          type: 'warning'
        })
      } else {
        this.$axios.post('/commentChild', this.clastform, {
          headers: {
            "Authorization": localStorage.getItem("token")
          }
        }).then(res => {
          this.$message({message: "回复成功", type: 'success'})
          this.reload();
          //发送完清空一下content
          this.cform.parentCid = ''
          this.commentId = ''
          this.cform.content = ''
          this.ccommentContent = ''
        })
      }*/
    },

    //跳转到收藏文章细节
    toDetail(bid) {
      this.$router.push({name: 'BlogDetail', params: {blogId: bid}})
      this.reload()
    },

    BeforeUploadVideo(file) {

      const v = file.size / 1024 / 1024 < 100
      if (!v) {
        this.$message.error('上传视频大小不能超过 100MB!')
        return false;
      }

      if (file) {
        this.videoFile.append('file', file); //  2. 上传之前，拿到file对象，并将它添加到刚刚定义的FormData对象中。
        this.$message.info("上传过程请耐心等待，成功后会自动提醒")
      } else {
        return false;
      }
    },
    UploadVideo() {
      const newData = this.videoFile;
      this.$axios.post('/videoUpload/' + this.blog.id, newData, {
        headers: {
          'Content-Type': 'multipart/ruleForm-data',
          "Authorization": localStorage.getItem("token")   //请求头携带的token
        }
      }).then(res => {
        this.$message({
          type: 'success',
          message: '上传成功'
        })
        this.reload()
      })
    },

  },
  created() {

    //先判断是否登录 没登陆跳转到登陆页面


    //注意是route  不是router  接收路由过来的参数
    const blogId = this.$route.params.blogId
    this.blog.id = blogId
    const _this = this

    //查询推荐文章
    this.$axios.get('/getSimilarBlogs/' + this.blog.id).then(res => {
      this.recommends = res.data.data;
    })

    //请求是否点过赞
    this.$axios.get('/isLike/' + blogId).then(res => {
      this.isLike = res.data.data.isLike
      // console.log("喜欢过吗 测试：" + this.isLike)
    })
    //请求是收藏
    this.$axios.get('/isCollected/' + blogId).then(res => {
      this.isCollected = res.data.data.isCollected
      // console.log("喜欢过吗 测试：" + this.isLike)
    })


    //设置留言的bid
    this.pform.bid = blogId

    //文章评论
    // this.$axios.get('/findParentComment/' + blogId).then(res => {
    //   this.pcomments = res.data.data.records
    // })
    this.page(1)

    //文章细节
    this.$axios.get('/blog/' + blogId).then(res => {
      const blog = res.data.data
      _this.blog.id = blog.id
      _this.blog.title = blog.title
      _this.blog.avatar = blog.avatar
      _this.blog.author = blog.author


      if (blog.video != null) {
        this.hasVideo = true
        this.playerOptions.sources[0].src = blog.video
      }

      //markdown-it  用于解析markdown
      //使用步骤 当然是先安装
      //  npm install markdown-it --save   (用于解析md)
      //  npm install github-markdown-css (md样式)

      //然后获取
      var MardownIt = require("markdown-it")
      var md = new MardownIt()

      //对content(.md)进行渲染
      var result = md.render(blog.content)
      //再赋值给content
      _this.blog.content = result
      //赋值后 还要再div中 绑定class 来获取样式


      //只有当blg的userid == 当前用户的id
      _this.ownBlog = (blog.userId === _this.$store.getters.getUser.id)

    })
    // //由于打开时页面不在顶部  手动刷新一下页面
    // location.reload();

    //生成分类标签
    this.$axios.get("/getMetas").then(res => {

      var meta = {label: ''}
      var metas = new Array();

      for (var i = 0; i < res.data.data.count; i++) {
        //牛啊牛啊
        meta = {}   //必须要清空一次  //只用下面这一句不够
        meta.label = res.data.data.labels[i]
        metas[i] = meta
      }
      this.metasFromBack = metas
    })
  }
}
</script>

<style scoped>


.commentLast {
  float: right;
  text-align: right;
}

.mblog {
  margin: auto;
  /*elementUi  文本框 样式*/
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 60%;
  min-height: 300px;
  padding: 20px 15px;
}

.mComment {
  margin: auto;
  /*elementUi  文本框 样式*/
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 60%;
  min-height: 100px;
  padding: 20px 15px;
}

.like {
  text-align: right;
}

.mpage {
  margin: 0 auto;
  text-align: center;
}

.commentTime {
  font-size: xx-small;
  font-weight: lighter;
}

.bauthor {
  text-align: right;
  font-weight: bolder;
}

.pcommentavatar {
  text-align: right;

}

.huifu {
  text-align: right;
}

.maincontent {
  position: relative;
  top: 100px;
}

.recommend {
  width: 50%;
  position: relative;
  left: 40px;
}

</style>